package com.glory.brepda.activity.mfg;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.MaterielAdapter;
import com.glory.brepda.adapter.MaterielListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpBody;
import com.glory.brepda.entity.EqpEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotLists;
import com.glory.brepda.entity.LotactionList;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.glory.brepda.utils.ShowDialog;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class ZJCCommonlyBeginActivity extends BaseActivity {

    @BindView(R.id.etTitle)
    FreeUI_ClearEditText etTitle;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.etWeight)
    FreeUI_ClearEditText etWeight;
    @BindView(R.id.tvBDNum)
    TextView tvBDNum;
    @BindView(R.id.tvpartName)
    TextView tvpartName;
    @BindView(R.id.tvPackageType)
    TextView tvPackageType;
    @BindView(R.id.tvRecipeID)
    TextView tvRecipeID;
    @BindView(R.id.tvMainQty)
    TextView tvMainQty;
    @BindView(R.id.tvStepDesc)
    TextView tvStepDesc;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private AddCarrierDataAdapter materielModelAdapter;
    private AddCarrierDataAdapter materielBoxAdapter;
    private MaterielListAdapter materielListAdapter;
    private MaterielAdapter materielAdapter;
    private List<String> mDurablelist;
    private String woid;
    private LotInfoEntity lotInfoBean;
    private boolean isetEqpWorkID = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_in_wb;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        etLot.requestFocus();
        initRecyclerView(rvMaterielModelList, this);
        initRecyclerView(rvMaterielBoxList, this);
        initRecyclerView(rvMaterielList, this);
        materielModelAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModelAdapter);
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);

        materielAdapter = new MaterielAdapter(null);
        materielAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielAdapter.isFirstOnly(true);
        rvMaterielList.setAdapter(materielAdapter);

        etEqpWorkID.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b && isetEqpWorkID) {
                    isetEqpWorkID = false;
                    etLot.requestFocus();
                }
            }
        });

        initEdit(etMaterielModel, s -> {
            if (s.equals("Submit")) {
                etMaterielModel.setText("");
                Submit();
                etMaterielModel.requestFocus();
                return;
            }

            if (mDurablelist == null) {
                showToast("请先扫描批次号!", false);
                return;
            }


            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            if (mDurablelist.contains(s)) {
                materielModelAdapter.getData().add(s);
                materielModelAdapter.notifyDataSetChanged();
            } else {
                showToast("当前载具不匹配!", false);
            }

        });

        initEdit(etMaterielBox, s -> {
            if (s.contains("Submit")) {
                etMaterielBox.setText("");
                Submit();
                etMaterielBox.requestFocus();
                return;
            }

            if (mDurablelist == null) {
                showToast("请先扫描批次号!", false);
                return;
            }


            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前料盒已添加到列表中", false);
                return;
            }

            materielBoxAdapter.getData().add(s);
            materielBoxAdapter.notifyDataSetChanged();
            etMaterielBox.setText("");
            etMaterielBox.requestFocus();
        });
        etLot.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().contains("Submit")) {
                    Submit();
                    etLot.setText(editable.toString().replace("Submit", ""));
                    etLot.requestFocus();
                    return;
                }
            }
        });
        etEqpWorkID.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().contains("Submit")) {
                    Submit();
                    etEqpWorkID.setText(editable.toString().replace("Submit", ""));
                    etEqpWorkID.requestFocus();
                    return;
                }
            }
        });
        initEdit(etLot, s -> {
            //获取lot信息
            if (s.contains("Submit")) {
                etLot.setText(s.replace("Submit", ""));
                return;
            }

            LotUtils.searchLotInfo(ZJCCommonlyBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {

                    if(StringUtils.isNotEmpty(response.getTip())){
                        ShowDialog.showDialog(ZJCCommonlyBeginActivity.this,response.getTip(),"制程风险提示");
                    }
                    lotInfoBean = response;
                    Constant.LIMITPACKAGETYPEQTY = response.getLIMITPACKAGETYPEQTY();
                    Constant.PACKAGETYPE = response.getPACKAGETYPE();
                    Constant.WIRESPEC = response.getWIRESPEC();
                    Constant.BDCODE = response.getBD_CODE();
                    Constant.PARTNAME = response.getLOT().getPARTNAME();
                    woid = response.getLOT().getWOID();
                    tvBDNum.setText(response.getWIRINGNO());
                    tvpartName.setText(response.getLOT().getPARTNAME());
                    tvPackageType.setText(response.getPACKAGETYPE());
                    tvStepDesc.setText(response.getLOT().getSTEPDESC());
                    tvMainQty.setText(response.getLOT().getMAINQTY());
                    tvPauseStatus.setText(response.getLOT().getHOLDSTATE());
                    etEqpWorkID.requestFocus();
                    mDurablelist = response.getDURABLELIST();
                    tvTitle.setText("开始作业" + "(" + response.getLOT().getSTEPDESC() + ")");
                    tvLotState.setText(response.getLOT().getSTATE());
                    materielModelAdapter.setNewData(mDurablelist);
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

        initEdit(etEqpWorkID, s -> {
            if (s.contains("Submit")) {
                etEqpWorkID.setText(s.replace("Submit", ""));
                return;
            }
            getWqpInfo(s);
        });

        rvMaterielModelList.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    etTitle.setText("");
                    etTitle.requestFocus();
                }
            }
        });

        initEdit(etTitle, s -> {
            if (s.contains("Submit")) {
                Submit();
                return;
            }
            etTitle.setText("");
            etTitle.requestFocus();
        });

    }

    private void getWqpInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<EqpEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpEntity>>
                (new TypeToken<BaseResponseBean<EqpEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(ZJCCommonlyBeginActivity.this, true, getSupportFragmentManager())) {
                    EqpEntity body = response.body().getResponse().getBody();
                    materielAdapter.setNewData(body.equipmentlist);
                    etTitle.requestFocus();
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<EqpEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTKITTING");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "EQPBYID");
        EqpBody eqpBody = new EqpBody("",eqpID,"");
        map.add("EQUIPMENT",new JsonParser().parse(new Gson().toJson(eqpBody)).getAsJsonObject());
        NetUtils.requestPostNet("IF.BREQUERYEQP", "Common", ZJCCommonlyBeginActivity.this, map, callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
//        if (actionControl("Submit23"))
//            return;
        Submit();
    }

    private void Submit() {
        if (tvLotState.getText().toString().equals("待投产")) {
            showToast("批次未投产，请联系计划部执行投产!", false);
            etTitle.setText("");
            etTitle.requestFocus();
            return;
        }

        if (tvLotState.getText().toString().equals("正在作业")) {
            showToast("批次正在作业，请直接操作出站功能!", false);
            etTitle.setText("");
            etTitle.requestFocus();
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(ZJCCommonlyBeginActivity.this, false, getSupportFragmentManager())) {
                    FreeApi_ToastUtils.showFreeToast("进站成功", ZJCCommonlyBeginActivity.this, true, 0);
                    etLot.setText("");
                    etEqpWorkID.setText("");
                    etWeight.setText("");
                    tvMainQty.setText("");
                    tvStepDesc.setText("");
                    tvpartName.setText("");
                    tvPackageType.setText("");
                    tvBDNum.setText("");
                    tvLotState.setText("");
                    etMaterielModel.setText("");
                    etMaterielBox.setText("");
                    materielModelAdapter.setNewData(null);
                    materielBoxAdapter.setNewData(null);
                    materielAdapter.setNewData(null);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                FreeApi_LogUtils.saveErrorMessages(response.getException(), "LOTTRACKIN");
                FreeApi_ToastUtils.showFreeToast("连接服务器失败", ZJCCommonlyBeginActivity.this, false, 0);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "DefaultTrackIn");
        map.addProperty("EQUIPMENTID", getText(etEqpWorkID));
        map.addProperty("ISCHECKSTEPAUTHORITY", true);
        map.addProperty("BDCODE", Constant.BDCODE);
        map.addProperty("LIMITPACKAGETYPEQTY", Constant.LIMITPACKAGETYPEQTY);
        map.addProperty("PACKAGETYPE", Constant.PACKAGETYPE);
        map.addProperty("PARTNAME", Constant.PARTNAME);
        map.addProperty("PARTTYPE", lotInfoBean.getLOT().getPARTTYPE());
        map.addProperty("CUSTOMERCODE",lotInfoBean.getLOT().getCUSTOMERCODE());
        map.addProperty("WIRESPEC", Constant.WIRESPEC);
        map.addProperty("WOID", woid);
//                map.add("DURABLELIST", new JsonParser().parse(new Gson().toJson(carrierList)).getAsJsonArray());
//                List<LotList> lotList = new ArrayList<>();
//                lotList.add(new LotList(lotID));
        List<LotLists> lotLists = new ArrayList<>();
        List<LotactionList> LotactionList = new ArrayList<>();
        lotLists.add(new LotLists(getText(etLot)));
        LotactionList.add(new LotactionList(getText(etLot), "", "", "", "", ""));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotLists)).getAsJsonArray());//传批次集合
        map.add("LOTACTIONLIST", new JsonParser().parse(new Gson().toJson(LotactionList)).getAsJsonArray());//传批次集合
        map.add("DURABLEIDLIST", new JsonParser().parse(new Gson().toJson(materielBoxAdapter.getData())).getAsJsonArray());
//                map.addProperty("LOTACTIONLIST",etLot.getText().toString());//传批次动作列表
        NetUtils.requestPostNet("IF.LOTTRACKIN", "GENERALLOTTRACKIN", ZJCCommonlyBeginActivity.this, map, callBack);

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                if (!tvLotState.getText().toString().equals("待投产") && !tvLotState.getText().toString().equals("正在作业")) {
                    etTitle.setText("");
                    etTitle.requestFocus();
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
}
